from flask import Flask, request, jsonify
import docker
from waitress import serve
import logging

# 创建一个logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于在控制台上打印日志
ch = logging.StreamHandler()

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(ch)
app = Flask(__name__)


@app.route('/')
def hello():
    return '<a href="https://gitee.com/yunwe/con-man"> ConMan 使用文档</a>'


@app.route('/update_container', methods=['POST'])
def create_container():
    data = request.get_json()
    token = "QP77ZUFXNO0PO9AWVPSYLS5WCXUSCA1NCL2BSLV8"

    logging.info(f"Received request: {data}")
    # 检查 token 是否存在并且是否匹配
    if 'token' not in data or data['token'] != token:
        return jsonify({'message': '未认证!'}), 401

    client = docker.DockerClient(base_url=data['dockerUrl'])

    # 检查是否存在同名的容器
    try:
        existing_container = client.containers.get(data['containerName'])
        # 如果存在，则停止并删除它
        existing_container.stop()
        existing_container.remove()
    except docker.errors.NotFound:
        # 如果容器不存在，可以继续
        pass
    except Exception as e:
        return jsonify({'error': str(e)}), 500

    # 处理 volumes 字段
    volumes = {k: {'bind': v, 'mode': 'rw'} for k, v in data['volumes'].items()}

    container = client.containers.run(
        image=data['image'],
        name=data['containerName'],
        volumes=volumes,
        environment=data['env'],
        network_mode=data['networkMode'],
        restart_policy={"Name": data['restart']},
        ports=data['ports'],
        detach=True
    )

    return jsonify({'message': 'Container created', 'container_id': container.short_id}), 201


if __name__ == '__main__':
    logger.info("ConMan 应用已正常启动!")
    serve(app, host='0.0.0.0', port=5000)
